/**
 * Copyright 2013 Bhushan
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package org.s4j.signals.core;

import java.lang.reflect.InvocationTargetException;

import org.s4j.signals.exception.ConnectionException;
import org.s4j.signals.exception.NoSuchSignalException;

/**
 * Enables custom invocation behaviour in case the invoked object is a signal or a slot.
 * 
 * @author Bhushan
 * 
 */
public final class InvocationVisitor {

    /**
     * In case the invocation visitor is asked to visit a SignalContainer, it implies that the a Signal has been
     * connected to a signal.
     * 
     * @param container
     *            contains the target signal that needs to be invoked
     * @param parameters
     *            parameters that need to be passed to the signal
     */
    public void visit(final SignalContainer container, final Object... parameters) {
        try {
            Bridge.emit(container.getObject(), container.getSignalName(), parameters);
        } catch (NoSuchSignalException e) {
            throw new ConnectionException(e);
        }
    }

    /**
     * In case the invocation visitor is asked to visit a SlogContainer, it implies that the Slot has been connected to
     * a Signal and needs to be invoked.
     * 
     * @param container
     *            contains the target slot that needs to be invoked.
     * @param parameters
     *            parameters that need to be passed to the target slot
     */
    public void visit(final SlotContainer container, final Object... parameters) {
        try {
            container.getMethod().invoke(container.getObject(), parameters);
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            throw new ConnectionException(e);
        }
    }
}
